import err from './error.js'

const storageUtils = {
  set (key, data) {
    return new Promise((resolve, reject) => {
      data = JSON.stringify(data)
      uni.setStorage({
        key: key,
        data: data,
        success: () => {
          resolve()
        },
        fail: (e) => {
          reject(err('STORAGE_SET_FAILED', e))
        }
      })
    })
  },
  
  get (key) {
    return new Promise((resolve, reject) => {
      uni.getStorage({
        key: key,
        success: (res) => {
          const data = JSON.parse(res.data)
          resolve(data)
        },
        fail: (e) => {
          // 若没有读取到内容，返回null
          resolve(null)
        }
      })
    })
  },
  
  remove (key) {
    return new Promise((resolve, reject) => {
      uni.removeStorage({
        key: key,
        success: (res) => {
          resolve()
        },
        fail: (e) => {
          reject(err('STORAGE_REMOVE_FAILED', e))
        }
      })
    })
  },
  
  // 获取信息
  info () {
    return new Promise((resolve, reject) => {
      uni.getStorageInfo({
        success (res) {
          resolve(res)
        },
        fail: (e) => {
          reject(err('STORAGE_INFO_FAILED', e))
        }
      })      
    })
  },
  
  // 获取
}

export default storageUtils